package com.base.cn.platform.os.common;

import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台权限工具类
 *
 * @author s.li
 * @date 2019/03/27
 */
public class AdminFunctionUtils {

    /**
     * 获取访问面包屑
     * @param uri
     * @param allFunctionList
     * @return
     */
    public static List<Map<String,Object>> getRequestLink(String uri, List<Map<String,Object>> allFunctionList){
        if(ObjectUtils.isNotEmpty(allFunctionList) && StringUtils.isNotEmpty(uri)){
            Map<String,Map<String,Object>> functionToUrlMaps = allFunctionList.stream().filter(e->StringUtils.isNotEmpty((String)e.get("functionUrl"))).collect(Collectors.toMap(e->(String)e.get("functionUrl"),e->e,(x,y)-> y));
            Map<BigDecimal,Map<String,Object>> functionToIdMap = allFunctionList.stream().collect(Collectors.toMap(e->new BigDecimal(e.get("id").toString()),e->e,(x,y)-> y));
            Map<String,Object> uriFunction = functionToUrlMaps.get(uri.split("\\?")[0]);
            if(ObjectUtils.isNotEmpty(uriFunction)){
                BigDecimal parentId = new BigDecimal(uriFunction.get("parentId").toString());
                List<Map<String,Object>> functionLink = new ArrayList<>();
                functionLink.add(uriFunction);
                while (true){
                    Map<String,Object> parentMap = functionToIdMap.get(parentId);
                    if(parentMap==null){
                        break;
                    }
                    parentId = new BigDecimal(parentMap.get("parentId").toString());
                    functionLink.add(0,parentMap);
                }
                if(ObjectUtils.isNotEmpty(functionLink)){
                    return functionLink;
                }
            }
        }
        return null;
    }
}
